package com.joseph.websocket;

import com.joseph.websocket.handler.*;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.UnorderedThreadPoolEventExecutor;

public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    UnorderedThreadPoolEventExecutor eventExecutor = new UnorderedThreadPoolEventExecutor(50, new DefaultThreadFactory("Business"));

    HealthCheckHandler healthCheckHandler = new HealthCheckHandler();

    UserAuthHandler userAuthHandler = new UserAuthHandler();

    WebSocketHandler webSocketHandler = new WebSocketHandler();

//    MetricHandler metricHandler = new MetricHandler();

    protected void initChannel(SocketChannel socketChannel) throws Exception {

        ChannelPipeline pipeline = socketChannel.pipeline();
        //
        //        //pipeline.addLast(new T1InboundHandler());
        //        //websocket协议本身是基于http协议的，所以这边也要使用http解编码器
                pipeline.addLast(new HttpServerCodec());
        //        //以块的方式来写的处理器
                pipeline.addLast(new ChunkedWriteHandler());
        //        //netty是基于分段请求的，HttpObjectAggregator的作用是将请求分段再聚合,参数是聚合字节的最大长度
                pipeline.addLast(new HttpObjectAggregator(1024 * 1024 * 1024));
        //        //ws://server:port/context_path
        //        //ws://localhost:9999/ws
        //        //参数指的是contex_path

        //pipeline.addLast(healthCheckHandler);

        pipeline.addLast(userAuthHandler);

        // 安装 MetricHandler
        //pipeline.addLast(metricHandler);


        //pipeline.addLast(new MyWebsocketHandler("/ws"));
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

        // pipeline.addLast(new T1Handler());
        //websocket定义了传递数据的6中frame类型
        pipeline.addLast(webSocketHandler);

//        pipeline.addLast(eventExecutor, new WebSocketHandler1());

//        pipeline.addLast(new T2Handler());
    }
}